<template>
  <div
    class="login-wrap"
    v-loading="pageStatus > 0"
    :element-loading-text="{ 1: '跳转授权页面中...', 2: '登录中...' }[pageStatus]"
  >
    <el-result
      v-if="pageStatus < 0"
      icon="error"
      title="登录出错！"
      :sub-title="{ [-1]: '获取授权地址失败', [-2]: '登录失败' }[pageStatus]"
    >
      <template #extra>
        <el-button type="primary" @click="onRetryClick">重试</el-button>
      </template>
    </el-result>
  </div>
</template>

<script setup>
import { ref, inject } from 'vue'

/**
 * 页面状态 0：初始状态，1：获取授权地址中，2：登录中, -1: 获取授权地址失败， -2：登录失败
 */
const pageStatus = ref(0)
const http = inject('http')
// query 中有 code 则登录
const urlSearchParams = new URLSearchParams(location.search)
const params = Object.fromEntries(urlSearchParams.entries())
if (params.code) {
  login(params.code)
} else {
  loadAuthUrl()
}

function login(code) {
  pageStatus.value = 2
  http
    .request({ url: 'auth/login-with-code', method: 'post', data: { code, from: 'admin' } })
    .then((data) => {
      location.href = import.meta.env.VITE_CONTEXT_PATH + '/'
    })
    .catch((err) => {
      pageStatus.value = -2
    })
}
function loadAuthUrl() {
  pageStatus.value = 1
  const redirectUrl = location.origin + import.meta.env.VITE_CONTEXT_PATH + '/login'
  http
    .request({ url: 'auth/auth-url', params: { redirectUrl } })
    .then((data) => {
      const { authUrl } = data

      console.log(data)
      location.href = authUrl
    })
    .catch((err) => {
      pageStatus.value = -1
    })
}
function onRetryClick() {
  loadAuthUrl()
}
</script>
<style lang="scss">
.login-wrap {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
